<template>
<!--   <el-checkbox-group v-model="checkList">
    <el-checkbox label="复选框 A">1</el-checkbox>
    <el-checkbox label="复选框 B">2</el-checkbox>
    <el-checkbox label="复选框 C">3</el-checkbox>
    <el-checkbox label="禁用" disabled></el-checkbox>
    <el-checkbox label="选中且禁用" disabled></el-checkbox>
  </el-checkbox-group>
  <el-button type="primary" @click="ceshi(checkList);" >测试</el-button> -->
<div>
	<div class="crumbs">
        <el-breadcrumb separator="/">
            <el-breadcrumb-item><i class="el-logo-menu"></i>商品</el-breadcrumb-item>
            <el-breadcrumb-item>商品属性</el-breadcrumb-item>
        </el-breadcrumb>
    </div>
    <!-- <div class="titleDiv">商品</div> -->
 		<!-- <hr/> -->
	<div style="margin: 10px 0;">商品名：<span style="font-weight: 700;">{{ product.name }}</span>
	</div>
	<hr/>
    <div class="titleDiv">属性 
    	<el-button type="primary" @click="editEntityForm()" :disabled="propertyList.length >= 2">添加属性</el-button>
    </div>
	<div v-if="propertyList && propertyList.length > 0">
		<el-checkbox-group v-model="checkList">
    		<el-card class="box-card" v-for="(item,index) in propertyList" :key="index">
			  	<div slot="header" class="clearfix">
			    	<span style="line-height: 36px;" >{{ item.name }}</span>
			    	<el-button size="small" @click="setTouch(item.id,0)"  v-if="item.status == '-1'" >启用</el-button>
            		<el-button size="small" type="danger" @click="setTouch(item.id,-1)"  v-if="item.status == '0'" >禁用</el-button>
            		<el-button size="small" type="warning" @click="updateEntityForm(item)">修改属性</el-button>
			    	<el-button style="float: right;" type="primary" @click="editEntityForm2(item.id)" :disabled="propertyLabelCache[item.id] && propertyLabelCache[item.id].length >= 8">添加标签</el-button>
			  	</div>
				
			  	<div v-for="(label,labelIndex) in propertyLabelCache[item.id]" :key="labelIndex">
			  		<el-checkbox :label="label.id">
				  		<img :src="label.img" style="width:50px;height:50px"/>
			  			<span style="margin: 0 20px;">{{ label.name }}</span>
			  		</el-checkbox>
			  		<!-- <input v-if="label.imgSwitch == 1" type="hidden" :name="label.id" value="34"/> -->
			  		<!-- <div v-if="label.imgSwitch == 1" class="hidden">{{ putCheckList(label.id) }}</div> -->
			  		<el-button style="float: right;" type="primary" size="tiny" @click="editEntityForm2(item.id,label)">编辑</el-button>
			  	</div>
				
			</el-card>
		</el-checkbox-group>
	</div>
	<div style="clear:both;"></div>
    <div slot="footer" style="margin-top:10px;width:100%">
        <el-button type="primary" style="float:right" @click="saveLabelList()">保存修改</el-button>
    </div>
	<!-- 添加属性 -->
	<el-dialog :title="propertyDialogTitle" :visible.sync="propertyDialog">
        <div style="text-align:center;">
            <div style="text-align:left;width:90%;margin:0 auto;">
                <el-form :model="entityForm" :rules="entityFormRule" ref="entityForm" label-width="100px" class="demo-ruleForm" style="width:90%;">
                     <el-form-item prop="id"  style="display:none;">
                       <el-input v-model="entityForm.id" placeholder="编号"  ></el-input>
                    </el-form-item>
                    <el-form-item prop="name"  label="名称">
                       <el-input v-model="entityForm.name" placeholder="名称" ></el-input>
                    </el-form-item>
                </el-form>
            </div>
        </div>
        <div style="clear:both;"></div>
        <div slot="footer" class="dialog-footer">
            <el-button @click="propertyDialog=false">取消</el-button>
            <el-button  type="primary" @click="saveOrUpdateEntityForm()">保存</el-button>
        </div>
    </el-dialog>
	<!-- 添加或者编辑标签 -->
    <el-dialog :title="propertyLabelDialogTitle" :visible.sync="propertyLabelDialog">
        <div style="text-align:center;">
            <div style="text-align:left;width:90%;margin:0 auto;">
                <el-form :model="entityForm2" :rules="entityFormRule2" ref="entityForm2" label-width="100px" class="demo-ruleForm" style="width:90%;">
                    <el-form-item prop="id"  style="display:none;">
                       <el-input v-model="entityForm2.id" placeholder="编号"  ></el-input>
                    </el-form-item>
                    <el-form-item prop="name"  label="标签名">
                       <el-input v-model="entityForm2.name" placeholder="标签名" ></el-input>
                    </el-form-item>
                    <el-form-item prop="imgSwitch"  label="显示方式">
						<el-radio-group v-model="entityForm2.imgSwitch">
						    <el-radio class="radio" label="0">只显示文字（默认）</el-radio>
							<el-radio class="radio" label="1">只显示图片</el-radio>
						</el-radio-group>
                    </el-form-item>
                    <el-form-item type="file" prop="img"  label="标签图片">
                        <div style="border:1px solid #bfcbd9;line-height:100px;color:#bfcbd9;height:100px;">
	                        <input type="file" id="uimg1" accept="image/gif,image/jpeg,image/bmp,image/png" @change="setValue1(uploadImg('#uimg1','#logo'))" style="position:absolute;left: 0px;right: 0px;top: 0px;opacity: 0;filter: Alpha(opacity=0);z-index: 2;height:80px;"/>
	                        <div id="logo" style="height:100%">
	                        	<span v-if="!entityForm2.img">标签图片</span>
	                        	<img v-else :src="entityForm2.img" style='width:100px;height: 100px;' />
	                    	</div>
                        </div>
                        <el-input v-show="false" v-model="entityForm2.img"></el-input>
                    </el-form-item>
                </el-form>
            </div>
        </div>
        <div style="clear:both;"></div>
        <div slot="footer" class="dialog-footer">
            <el-button @click="propertyLabelDialog=false">取消</el-button>
            <el-button  type="primary" @click="saveOrUpdateEntityForm2()">保存</el-button>
        </div>
    </el-dialog>
</div>
</template>

<script>
  import $ from 'jquery';
  import Vue from 'vue';

  export default{
    data(){
	  return {
		row: null,
		productId:'',
		product:{},
		productName:'',
		propertyList:[],
		propertyDialogTitle:'',
		propertyDialog:false,
		entityForm:{       //属性form
		  id:'',
		  name:'',
		  productId:'',
		},
		entityFormRule:{   //添加属性规则
		  name: [
            {required: true, message: '请输入属性名', trigger: 'blur'}
          ],
		},
		propertyLabelCache:{},  //标签列表
		propertyLabelDialogTitle:'',
		propertyLabelDialog:false,
		entityForm2:{      //标签form
		  id:'',
		  name:'',
		  propertyId:'',
		  img:'',
		  status:0,
		  imgSwitch:'0',
		},
		entityFormRule2:{
		  name: [
            {required: true, message: '请输入标签名', trigger: 'blur'}
          ],
          img: [
            {required: true, message: '请上传标签图片哦', trigger: 'blur'}
          ],
          imgSwitch: [
            {required: true, message: '请选择展示方式哦', trigger: 'blur'}
          ],
		},
		checkList:[],
	  }
    },
    created(){
	  let self = this;
	  this.row = this.$route.params.product
	  if(this.row&&this.row.id){
		this.product = this.$route.params.product
		this.productId = this.product.id
		this.productName = this.product.name

		self.checkList.length = 0;
		self.getPropertyListByProductId();

	  }else{
		self.productId = localStorage.getItem("productId");
		if(!self.productId) {
		  self.$notify({title: '提示',message:"请从商品列表进入",type: 'error'});
		  window.location.hash = "product";
		}else{
		  self.checkList.length = 0;
		  self.getProductById();
		  self.getPropertyListByProductId();
		}
	  }
	  console.log(this.row)
    },
	mounted(){
	  this.reflushPropertyLabelCache();  //刷新商品标签数据库
	},
	methods:{
		ceshi(a){
		  console.log(a)
		},
		getProductById(){	//根据商品品ID查找对应产品
			let self = this;
			var productId = self.productId;
			if (!productId) {
				productId = self.productId = localStorage.getItem("productId");
			}
			// console.log(productId);
			if (self.productId) {
				self.myajax("/product/get/" + productId,{},function(data){
					if (data && data.code == 1000) {
						self.product = data.data;
						console.log(self.product);
					}else{
						self.$notify({title: '提示',message:(data.massage == null?'获取产品信息失败':data.massage),type: 'error'});
					}
				})
			}
		},
		getPropertyListByProductId(){	//根据商品ID查找商品属性列表
			let self = this;
			var productId = self.productId;
			if (!productId) {
				productId = self.productId = localStorage.getItem("productId");
			}
			if (productId) {
				self.myajax("/property/listByProductId/" + productId,{},function(data){
					if (data && data.code == 1000) {
						console.log('PropertyList')
						console.log(data)
						self.propertyList = data.data;
						return data.data;
					}else{
						self.$notify({title: '提示',message:(data.massage == null?'获取属性列表失败':data.massage),type: 'error'});
					}
				})
			}
			return null;
		},
		getPropertyLabelListByPropertyId(propertyId){	//根据商品属性ID查找商品属性标签列表
			let self = this;
			if (propertyId) {
				// self.checkList = []
				self.myajax("/propertyLabel/listByPropertyId/" + propertyId,{},function(data){
					if (data && data.code == 1000) {
						self.propertyLabelCache[propertyId] = data.data;
						console.log(data.data)
						for(var i in data.data){
							if( data.data[i].status && data.data[i].status == 1){
								self.checkList.push(data.data[i].id);
							}
						}
						return data.data;
					}else{
						self.$notify({title: '提示',message:(data.massage == null?'获取标签列表失败':data.massage),type: 'error'});
					}
				});
			}
			return null;
		},
		editEntityForm(){	//打开添加商品属性弹框
			let self = this;
			self.entityForm.id = "",
			self.entityForm.name = "",
			self.entityForm.productId = self.productId;
			self.propertyDialog = "添加属性";
			self.propertyDialog = true;
		},
		updateEntityForm(item){  //打开修改商品属性弹框
			this.entityForm.id = item.id,
			this.entityForm.name = item.name,
			this.entityForm.productId = this.productId;
			this.propertyDialog = "修改属性";
			this.propertyDialog = true;
		},
		saveOrUpdateEntityForm(){    //保存、修改商品属性
			let self = this;
			self.$refs['entityForm'].validate((valid) => {
				if(valid){      //验证过true，不通过false
					var url = "/property/create";
					if(self.entityForm.id){
						url = "/property/update";
					}
					self.myajax(url,self.entityForm,function(data){
						if (data &&　data.code == 1000) {
							self.getPropertyListByProductId(self.entityForm.productId);
							self.$notify({title: '提示',message:"操作成功",type: 'success'});
							self.propertyDialog = false;
						}else{
							self.$notify({title: '提示',message:(data.massage == null?'操作失败':data.massage),type: 'error'});
						}
					})
				}
			})
		},
		editEntityForm2(propertyId,label){		//添加或编辑标签
			let self = this;
			if (propertyId) {
				self.entityForm2.propertyId = propertyId;
				if (label && label.id) {   
					self.propertyLabelDialogTitle = "修改标签";
					self.entityForm2.id = label.id;
					self.entityForm2.name = label.name;
					self.entityForm2.img = label.img;
					self.entityForm2.imgSwitch = label.imgSwitch == null ? "0" : label.imgSwitch.toString() ;
				}else{      
					self.propertyLabelDialogTitle = "添加标签";
					self.entityForm2.id = "",
					self.entityForm2.name = "",
					self.entityForm2.img = "",
					self.entityForm2.imgSwitch = "0"; //默认只显示文字
				}
				self.propertyLabelDialog = true;
			}else{
				console.log("Property.vue -> editEntityForm2 -> id = null");
				self.$notify({title: '提示',message:"未知错误，请联系系统管理员",type: 'error'});
			}
		},
		saveOrUpdateEntityForm2(){	//创建
			let self = this;
			console.log(this.entityForm2)
			self.$refs['entityForm2'].validate((valid) => {
				if (valid) {
					var url = "/propertyLabel/create";
					if (self.entityForm2.id) {
						url = "/propertyLabel/update";
					}
					self.myajax(url,self.entityForm2,function(data){
						if (data &&　data.code == 1000) {
							self.getPropertyLabelListByPropertyId(self.entityForm2.propertyId);
							self.$notify({title: '提示',message:"操作成功",type: 'success'});
							self.propertyLabelDialog = false;
						}else{
							self.$notify({title: '提示',message:(data.massage == null?'操作失败':data.massage),type: 'error'});
						}
					})
				}
			})
		},
		reflushPropertyLabelCache(){	//刷新缓存
			let self = this;
			self.propertyLabelCache = {};
			if (self.propertyList && self.propertyList.length > 0) {
				for(var i in self.propertyList){
					var obj = self.propertyList[i];
					if (obj && obj.id) {
						self.getPropertyLabelListByPropertyId(obj.id)
					}
				}
			}else{
				// for(var i in propertyLabelCache){
				// 	if(propertyLabelCache[i]){
				// 		propertyLabelCache[i].length = 0;
				// 	}
				// }
				console.log("[warn] The propertyList is null ");
			}
		},
		setValue1(val){	//图片上传相关
			console.log(val)
			if (val) {
				this.entityForm2.img = Vue.prototype.$host + val;
			}else{
				this.entityForm2.img = "";
			}
		},
		saveLabelList(){   //最底下的保存修改
			let self = this;
			if (self.productId) {
				if (self.checkList) {
					var paramJson = {};
					paramJson.ids = self.checkList;
					console.log(paramJson)
					self.myajax("/propertyLabel/setImgSwitchByProductId/" + self.productId , paramJson, function(data){
						if (data &&　data.code == 1000) {
							self.$notify({title: '提示',message:"操作成功",type: 'success'});
							self.$router.go(-1)
						}else{
							self.$notify({title: '提示',message:(data.massage == null?'操作失败':data.massage),type: 'error'});
						}
					})
				}else{
					console.log("Property.vue -> saveLabelList -> checkList = null");
					self.$notify({title: '提示',message:"未知错误，请联系系统管理员",type: 'error'});
				}
			}else{
				console.log("Property.vue -> saveLabelList -> productId = null");
				self.$notify({title: '提示',message:"未知错误，请联系系统管理员",type: 'error'});
			}
		},
		setTouch(propertyId,type){	//启用、禁用属性
			let self = this;
			if (propertyId && !isNaN(type)) {
				var ids = [];
				ids.push(propertyId);
				var dto = {};
				dto.ids = ids;
				dto.type = type;
				var msg ;
				if (type == 0) {
					msg = "启用";
				}else if (type == -1) {
					msg = '禁用';
				}else{
					console.log("Property.vue -> setTouch -> type = " + type);
					self.$notify({title: '提示',message:"未知错误，请联系系统管理员",type: 'error'});
				}
				if (type == 0 || type == -1) {
					self.myajax("/property/touch",dto,function(data){
						if (data &&　data.code == 1000) {
							self.$notify({title: '提示',message: msg + "成功",type: 'success'});
							self.getPropertyListByProductId();	//刷新数据
						}else{
							self.$notify({title: '提示',message:(data.massage == null?'操作失败':data.massage),type: 'error'});
						}
					});
				}
			}
		},
	}
}
</script>

<style scoped>
	.titleDiv{
		margin-top: 10px;
		margin-bottom: 10px;
	}
	img{
		max-width: 100%;
	}
	checkbox-before{
		width: 20px;
		height: 20px;
	}
	.hidden{
		display: none;
	}
</style>
